package com.bringspring.system.base.controller;

import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.Pagination;
import com.bringspring.common.base.vo.ListVO;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.exception.DataException;
import com.bringspring.common.model.visiual.ColumnDataModel;
import com.bringspring.common.model.visiual.ColumnListField;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.ReflectionUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.common.util.context.SpringContext;
import com.bringspring.system.base.entity.ModuleColumnEntity;
import com.bringspring.system.base.entity.ModuleEntity;
import com.bringspring.system.base.model.column.*;
import com.bringspring.system.base.model.module.PropertyJsonModel;
import com.bringspring.system.base.service.ModuleColumnService;
import com.bringspring.system.base.service.ModuleService;
import com.bringspring.system.base.util.JsonUtilEx;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * 列表权限
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月27日 上午9:18
 */
@Api(tags = "列表权限", value = "ModuleColumn")
@Validated
@RestController
@RequestMapping("/api/system/ModuleColumn")
public class ModuleColumnController {

    @Autowired
    private ModuleColumnService moduleColumnService;
    @Autowired
    private ModuleService moduleService;

    /**
     * 获取列表权限信息列表
     *
     * @param moduleId   功能主键
     * @param pagination 分页参数
     * @return ignore
     */
    @ApiOperation("获取列表权限列表")
    @GetMapping("/{moduleId}/Fields")
    public ActionResult getList(@PathVariable("moduleId") String moduleId, Pagination pagination) {
        List<ModuleColumnEntity> list = moduleColumnService.getList(moduleId, pagination);
        List<ColumnListVO> voList = JsonUtil.getJsonToList(list, ColumnListVO.class);
        voList.stream().forEach(t-> {
            if (StringUtils.isNotEmpty(t.getEnCode())) {
                t.setEnCode(StringUtils.isNotEmpty(t.getEnCode()) ? t.getEnCode().replace("jsbos_" + t.getBindTable() + "_jsbos_", "") : "");
            }
        });
        ListVO<ColumnListVO> vo = new ListVO<>();
        vo.setList(voList);
        return ActionResult.success(vo);
    }

    /**
     * 菜单列表权限
     *
     * @param moduleId 功能主键
     * @return ignore
     */
    @ApiOperation("菜单列表权限")
    @GetMapping("/{moduleId}/FieldList")
    public ActionResult fieldList(@PathVariable("moduleId") String moduleId) {
        List<Map<String, String>> list = new ArrayList<>();
        // 得到菜单id
        ModuleEntity entity = moduleService.getInfo(moduleId);
        if (entity != null) {
            PropertyJsonModel model = JsonUtil.getJsonToBean(entity.getPropertyJson(), PropertyJsonModel.class);
            if (model == null) {
                model = new PropertyJsonModel();
            }
            // 得到bean
            Object bean = SpringContext.getBean("visualdevServiceImpl");
            Object method = ReflectionUtil.invokeMethod(bean, "getInfo", new Class[]{String.class}, new Object[]{model.getModuleId()});
            Map<String, Object> map = JsonUtil.entityToMap(method);
            boolean isPc = entity.getCategory().equalsIgnoreCase("web");
            if (map!=null){
                Object columnData = isPc ? map.get("columnData") : map.get("appColumnData") ;
                if (Objects.nonNull(columnData)){
                    ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData.toString(), ColumnDataModel.class);
                    List<ColumnListField> columnListFields = JsonUtil.getJsonToList(columnDataModel.getDefaultColumnList(), ColumnListField.class);
                    if (Objects.nonNull(columnListFields)) {
                        columnListFields.stream().forEach(col -> {
                            Map<String, String> dataMap = new HashMap<>();
                            dataMap.put("field", col.getProp());
                            dataMap.put("fieldName", col.getLabel());
                            list.add(dataMap);
                        });
                    }
                }
            }
        }


//        if (map != null && map.containsKey("formData")) {
//            // 需要排除的key
//            String[] filterKey = new String[]{"PsdInput", "colorPicker", "rate", "slider", "divider",
//                    "uploadImg", "uploadFz", "editor", "ComText", "relationFormAttr", "popupAttr", "groupTitle"};
//            List<String> filterKeyList = Arrays.asList(filterKey);
//            FormDataModel formDataModel = JsonUtil.getJsonToBean(String.valueOf(map.get("formData")), FormDataModel.class);
//            List<FieLdsModel> fieLdsModelList = JsonUtil.getJsonToList(formDataModel.getFields(), FieLdsModel.class);
//            RecursionForm recursionForm = new RecursionForm();
//            recursionForm.setList(fieLdsModelList);
//            recursionForm.setTableModelList(JsonUtil.getJsonToList(String.valueOf(map.get("tables")), TableModel.class));
//            List<FormAllModel> formAllModel = new ArrayList<>();
//            FormCloumnUtil.recursionForm(recursionForm, formAllModel);
//            for (FormAllModel allModel : formAllModel) {
//                if (FormEnum.mast.getMessage().equals(allModel.getKeyName())) {
//                    FormColumnModel formColumnModel = allModel.getFormColumnModel();
//                    FieLdsModel fieLdsModel = formColumnModel.getFieLdsModel();
//                    long count = filterKeyList.stream().filter(t -> fieLdsModel != null && fieLdsModel.getConfig()!=null && t.equals(fieLdsModel.getConfig().getKeyName())).count();
//                    if (count < 1) {
//                        if (fieLdsModel != null && StringUtil.isNotEmpty(fieLdsModel.getVModel())) {
//                            Map<String, String> map1 = new HashedMap<>();
//                            map1.put("field", fieLdsModel.getVModel());
//                            map1.put("fieldName", fieLdsModel.getConfig().getLabel());
//                            list.add(map1);
//                        }
//                    }
//                } else if (FormEnum.mastTable.getMessage().equals(allModel.getKeyName())) {
//                    FormMastTableModel formColumnModel = allModel.getFormMastTableModel();
//                    FieLdsModel fieLdsModel = formColumnModel.getMastTable().getFieLdsModel();
//                    long count = filterKeyList.stream().filter(t -> fieLdsModel != null && fieLdsModel.getConfig() != null && t.equals(fieLdsModel.getConfig().getKeyName())).count();
//                    if (count < 1) {
//                        if (fieLdsModel != null && StringUtil.isNotEmpty(fieLdsModel.getVModel())) {
//                            Map<String, String> map1 = new HashedMap<>();
//                            map1.put("field", fieLdsModel.getVModel());
//                            map1.put("fieldName", fieLdsModel.getConfig().getLabel());
//                            list.add(map1);
//                        }
//                    }
//                }
//
///// 后面会用到
////                else if (FormEnum.table.getMessage().equals(allModel.getKeyName())) {
////                    FormColumnTableModel childList = allModel.getChildList();
////                    List<FormColumnModel> childList1 = childList.getChildList();
////                    for (FormColumnModel formColumnModel : childList1) {
////                        FieLdsModel fieLdsModel = formColumnModel.getFieLdsModel();
////                        if (StringUtil.isNotEmpty(fieLdsModel.getVModel())) {
////                            Map<String, String> map1 = new HashedMap<>();
////                            map1.put("field", fieLdsModel.getVModel());
////                            map1.put("fieldName", fieLdsModel.getConfig().getLabel());
////                            list.add(map1);
////                        }
////                    }
////                }
/////
//            }
//        }
        return ActionResult.success(list);
    }

    /**
     * 获取列表权限信息
     *
     * @param id 主键值
     * @return ignore
     * @throws DataException ignore
     */
    @ApiOperation("获取列表权限信息")
    @GetMapping("/{id}")
    public ActionResult<ModuleColumnInfoVO> info(@PathVariable("id") String id) throws DataException {
        ModuleColumnEntity entity = moduleColumnService.getInfo(id);
        ModuleEntity moduleEntity = moduleService.getInfo(entity.getModuleId());
        if (moduleEntity != null && moduleEntity.getType() == 2 && entity.getFieldRule() == 1 && StringUtils.isNotEmpty(entity.getBindTable())) {
            entity.setEnCode(entity.getEnCode().replace("jsbos_" + entity.getBindTable() + "_jsbos_", ""));
        }
        ModuleColumnInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, ModuleColumnInfoVO.class);
        return ActionResult.success(vo);
    }

    /**
     * 新建列表权限
     *
     * @param moduleColumnCrForm 实体对象
     * @return ignore
     */
    @ApiOperation("新建列表权限")
    @PostMapping
    public ActionResult create(@RequestBody @Valid ModuleColumnCrForm moduleColumnCrForm) {
        ModuleEntity moduleEntity = moduleService.getInfo(moduleColumnCrForm.getModuleId());
        ModuleColumnEntity entity = JsonUtil.getJsonToBean(moduleColumnCrForm, ModuleColumnEntity.class);
        if (moduleEntity != null && moduleEntity.getType() == 2 && entity.getFieldRule() == 1 && StringUtils.isNotEmpty(entity.getBindTable())) {
            String enCode = "jsbos_" + entity.getBindTable() + "_jsbos_" + entity.getEnCode();
            entity.setEnCode(enCode);
        }
        if (moduleColumnService.isExistByEnCode(entity.getModuleId(), entity.getEnCode(), entity.getId())) {
            return ActionResult.fail("字段名称不能重复");
        }
        moduleColumnService.create(entity);
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 更新列表权限
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("更新列表权限")
    @PutMapping("/{id}")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ModuleColumnUpForm moduleColumnUpForm) {
        ModuleEntity moduleEntity = moduleService.getInfo(moduleColumnUpForm.getModuleId());
        ModuleColumnEntity entity = JsonUtil.getJsonToBean(moduleColumnUpForm, ModuleColumnEntity.class);
        if (moduleEntity != null && moduleEntity.getType() == 2 && entity.getFieldRule() == 1 && StringUtils.isNotEmpty(entity.getBindTable())) {
            String enCode = "jsbos_" + entity.getBindTable() + "_jsbos_" + entity.getEnCode();
            entity.setEnCode(enCode);
        }
        if (moduleColumnService.isExistByEnCode(entity.getModuleId(), entity.getEnCode(), id)) {
            return ActionResult.fail("字段名称不能重复");
        }
        boolean flag = moduleColumnService.update(id, entity);
        if (!flag) {
            return ActionResult.success(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 删除列表权限
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("删除列表权限")
    @DeleteMapping("/{id}")
    public ActionResult delete(@PathVariable("id") String id) {
        ModuleColumnEntity entity = moduleColumnService.getInfo(id);
        if (entity != null) {
            moduleColumnService.delete(entity);
            return ActionResult.success(MsgCode.SU003.get());
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }

    /**
     * 更新列表权限状态
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("更新列表权限状态")
    @PutMapping("/{id}/Actions/State")
    public ActionResult upState(@PathVariable("id") String id) {
        ModuleColumnEntity entity = moduleColumnService.getInfo(id);
        if (entity.getEnabledMark() == null || "1".equals(String.valueOf(entity.getEnabledMark()))) {
            entity.setEnabledMark(0);
        } else {
            entity.setEnabledMark(1);
        }
        boolean flag = moduleColumnService.update(id, entity);
        if (!flag) {
            return ActionResult.success(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 批量新建
     *
     * @param columnBatchForm 权限模型
     * @return ignore
     */
    @ApiOperation("批量新建列表权限")
    @PostMapping("/Actions/Batch")
    public ActionResult batchCreate(@RequestBody @Valid ColumnBatchForm columnBatchForm) {
        List<ModuleColumnEntity> entitys = columnBatchForm.getColumnJson() != null ? JsonUtil.getJsonToList(columnBatchForm.getColumnJson(), ModuleColumnEntity.class) : new ArrayList<>();
        List<String> name = new ArrayList<>();
        for (ModuleColumnEntity entity : entitys) {
            entity.setModuleId(columnBatchForm.getModuleId());
            if (moduleColumnService.isExistByEnCode(entity.getModuleId(), entity.getEnCode(), null)) {
                return ActionResult.fail(MsgCode.EXIST002.get());
            }
            if (name.contains(entity.getEnCode())) {
                return ActionResult.fail(MsgCode.EXIST002.get());
            }
            name.add(entity.getEnCode());
        }
        moduleColumnService.create(entitys);
        return ActionResult.success(MsgCode.SU001.get());
    }
}
